import { Component, OnInit, Input } from '@angular/core';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { MerchantService } from '../../service/merchant.service';
import { RoleRight } from '../../../kalend';
import { PlatformuserService } from '../../service/platformuser.service';
import { config } from '../../../config';
import { Router, ActivatedRoute } from '@angular/router';
import { CommonService } from 'src/app/service/common.service';
import { DatadictionaryService } from 'src/app/service/datadictionary.service';
@Component({
  selector: 'app-restaurantlist',
  templateUrl: './restaurantlist.component.html',
  styleUrls: ['./restaurantlist.component.scss'],
  providers: [MerchantService, PlatformuserService, DatadictionaryService]
})
export class RestaurantlistComponent implements OnInit {
  user: any = RoleRight.getStorage();
  name: any;
  pageIndex = 1;
  pageSize = 10;
  total = 1;
  dataSet = [];
  loading = true;
  isOkLoading = false;
  isVisible = false;
  legaluserItems: Array<any> = [];
  agentItems: Array<any> = [];
  doc: any = {};
  info: any = {
    imgs: []
  };
  sdate: any;
  edate: any;
  usdate: any;
  uedate: any;
  status;
  state;
  bondstatus;
  mid: any;
  // tslint:disable-next-line:max-line-length
  cuisineItems: Array<any> = [];
  statuslist = [{ key: 'all', value: '全部' }, { key: 1, value: '有效' }, { key: 0, value: '禁用' }];
  // tslint:disable-next-line:max-line-length
  statelist = [{ key: 'all', value: '全部' }, { key: 0, value: '未申请' }, { key: 1, value: '待审核' }, { key: 2, value: '已通过' }, { key: 9, value: '已退回' }];
  bondstatuslist = [{ key: 'all', value: '全部' }, { key: 1, value: '未缴纳' }, { key: 1, value: '已缴纳' }, { key: 9, value: '已退款' }];
  action = config.imageuploadurl;

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result.toString()));
    reader.readAsDataURL(img);
  }

  constructor(private service: MerchantService, private msg: NzMessageService, private puser: PlatformuserService,
    private router: Router, private commonservice: CommonService, private datadic: DatadictionaryService) { 
      // 获取菜系
     this.datadic.queryByKey('cuisine').then((res) => {
      this.cuisineItems = res;
    });
    }

  ngOnInit() {
    this.searchData();
     
  }

  searchData(reset: boolean = false): void {
    this.loading = true;
    this.service.query({
      offset: this.pageIndex,
      limit: this.pageSize,
      name: this.name,
      status: this.status,
      state: this.state,
      bondstatus: this.bondstatus,
      // regstarttime: this.sdate,
      // regendtime: this.edate,
      upstarttime: this.usdate,
      upendtime: this.uedate
    }).then((res) => {
      this.loading = false;
      this.total = res.total;
      this.dataSet = res.rows;
    });
  }
  /** 获取负责人 */
  getuser(mid?: any) {
    this.puser.getuser('ct', mid).then((res) => {
      this.legaluserItems = res || [];
    });
    this.puser.getuser('ds', mid).then((res) => {
      this.agentItems = res || [];
    });
  }
  /**新增 */
  add() {
    this.getuser();
    this.doc.createuser = this.user._id;
    this.isVisible = true;
    // this.doc.percapita=0;
    // this.yjbl="根据系统计算建议佣金比例为10%";
  }

  /**修改 */
  edit(id: any) {
    this.getuser(id);
    this.isVisible = true;
    this.service.queryById(id).then((res) => {
      // 调用计算商户佣金比例接口
      // this.merchantwineservice.calcmerchantrate({ mid: id }).then((r) => {
      //   this.yjbl = "根据系统计算建议佣金比例为" + r.merchantrate + "%";
      // });
      this.info = res.info;
      delete res.info;
      this.doc = res;
    });
  }
  calsIpputRate() {
    const rjmoney = this.doc.percapita;
    let merchantrate = 0;
    if (rjmoney >= 40 && rjmoney < 50) {
      merchantrate = 13;
    }

    if (rjmoney >= 50 && rjmoney < 60) {
      merchantrate = 12;
    }

    if (rjmoney >= 60 && rjmoney < 70) {
      merchantrate = 11;
    }

    if (rjmoney >= 70 && rjmoney < 80) {
      merchantrate = 10;
    }

    if (rjmoney >= 80 && rjmoney < 90) {
      merchantrate = 9;
    }

    if (rjmoney >= 90 && rjmoney < 100) {
      merchantrate = 8;
    }
    if (rjmoney >= 100) {
      merchantrate = 7;
    }
    this.doc.rate = merchantrate;
  }
  /**禁用 */
  lock(id: any) {
    this.service.lock(id).then((res) => {
      this.searchData();
    });
  }
  /**启用 */
  open(id: any) {
    this.service.open(id).then((res) => {
      this.searchData();
    });
  }
  /** 消费账单 */
  orderlist(id: any) {
    if (id) {
      this.router.navigate(['/salesmanage/settlementrecordsMid', id]);
    } else {
      this.msg.warning('请先为餐厅开通后台账户');
    }
  }
  handleOk(): void {
    this.isOkLoading = true;
    if (!this.doc.name || this.doc.name === '') {
      this.msg.warning('请填写餐厅名称');
    } else if (!this.doc.cuisine) {
      this.msg.warning('请选择所属菜系');
    } else if (!this.doc.rate) {
      this.msg.warning('请设置佣金比例');
    } else if (!this.doc.percapita) {
      this.msg.warning('请设置人均消费');
    } else if (!this.doc.logoimage) {
      this.msg.warning('请设置餐厅logo');
    } else {
      this.doc.info = this.info;
      this.service.save(this.doc).then((res) => {
        this.searchData();
        this.msg.success('保存成功！');
        this.isVisible = false;
        this.doc = {};
        this.info = {
          imgs: []
        };
      });
    }
  }
  handleCancel(): void {
    this.isVisible = false;
    this.doc = {};
    this.info = {
      imgs: []
    };
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg' || 'image/png';
    if (!isJPG) {
      this.msg.error('您只能上传图片文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      this.msg.error('图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
  }
  handleChange(info: { file: UploadFile }, type: any): void {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, (img: string) => {
        this.loading = false;
        if (info.file && info.file.response && info.file.response.data) {
          if (type === 'logo') {
            this.doc.logoimage = info.file.response.data
          } else if (type === 'img') {
            this.info.imgs.push(info.file.response.data);
          }
        }
      });
    }
  }
  /** 邀请记录 */
  inverlist(id: any) {
    if (id) {
    // this.router.navigate([`/manage/userwinhistory/${id}`]);
    this.router.navigate(['/sysset/inverhistory', id]);
    } else {
      this.msg.warning('请先关联小程序账号');
    }
  }
  // 微信设置
  payset(id: any) {
    if (id) {
      // this.router.navigate(['/manage/payset', id],);
      window.open('/#/manage/payset/' + id)
    } else {
      this.msg.warning('请先关联小程序账号');
    }
  }
  deleteimg(img: any) {
    this.commonservice.confirm('确认删除吗？', () => {
      this.info.imgs.splice(img, 1);
    });
  }
}
